<template>
  <el-checkbox
    v-if="props.multiple"
    :indeterminate="isIndeterminate"
    v-model="checkAll"
    @change="handleCheckAllChange"
    style="margin-right: 12px"
    >全选</el-checkbox
  >
  <el-checkbox-group
    :model-value="modelValue"
    @update:modelValue="updateValue"
    v-if="props.multiple"
    @change="handleCheckedChange"
  >
    <el-checkbox
      v-for="item in data"
      :label="item.tenant_id"
      :key="item.tenant_id"
    >
      {{ item.title }}
    </el-checkbox>
  </el-checkbox-group>

  <el-radio-group
    :model-value="modelValue"
    @update:modelValue="updateValue"
    v-if="!props.multiple"
  >
    <el-radio
      v-for="item in data"
      :label="item.tenant_id"
      :key="item.tenant_id"
    >
      {{ item.title }}
    </el-radio>
  </el-radio-group>

  <!-- <el-select
    :model-value="modelValue"
    placeholder="请选择"
    @update:modelValue="updateValue"
    :style="{ width: props.width }"
    filterable
    :multiple="props.multiple"
  >
    <el-option
      v-for="item in data"
      :key="item.tenant_id"
      :label="item.title"
      :value="item.tenant_id"
    />
  </el-select> -->
</template>

<script setup>
  import { ref, onMounted, nextTick } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { pageMyTenant } from '@/api/company';

  const emit = defineEmits(['update:modelValue', 'loaded']);

  const props = defineProps({
    multiple: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: '300px'
    },
    all: {
      type: String,
      default: '0'
    },
    /** 选中的租户ID */
    modelValue: {
      type: [Number, String, Array],
      default: () => []
    }
  });

  /** 站点数据 */
  const data = ref([]);

  const isIndeterminate = ref(true);
  const checkAll = ref(false);

  /**
   *  完善这2个代码，handleCheckAllChange是点击了全选，要全选下面那个checkbox
   * handleCheckedChange是下面那个checkbox点击了，要更新全选的checkbox状态
   * */
  /** 全选/取消全选 */
  const handleCheckAllChange = (val) => {
    const allTenantIds = data.value.map((item) => item.tenant_id);
    const newValue = val ? allTenantIds : [];
    isIndeterminate.value = false;
    updateValue(newValue); // 触发更新
  };

  /** 子项选中状态变化 */
  const handleCheckedChange = (value) => {
    const checkedCount = value.length;
    const total = data.value.length;
    checkAll.value = checkedCount === total;
    isIndeterminate.value = checkedCount > 0 && checkedCount < total;
    updateValue(value);
  };

  /** 本地缓存 key */
  const getCacheKey = () => (props.multiple ? 'tenant_multi' : 'tenant_single');

  /** 更新选中数据 */
  const updateValue = (value) => {
    localStorage.setItem(getCacheKey(), JSON.stringify(value));
    emit('update:modelValue', value);
  };

  /** 获取站点数据并设置默认值 */
  const loadSites = async () => {
    try {
      const res = await pageMyTenant({ all: props.all });
      data.value = res || [];

      if (data.value.length > 0) {
        // 优先用缓存
        const cacheStr = localStorage.getItem(getCacheKey());
        console.log(cacheStr, '是什么');
        let cache = null;
        if (cacheStr) {
          try {
            cache = JSON.parse(cacheStr);
          } catch {
            cache = null;
          }
        }

        let finalValue = null;

        if (props.multiple) {
          // 多选：缓存必须是非空数组才算有效
          if (Array.isArray(cache) && cache.length > 0) {
            finalValue = cache;
          }
        } else {
          // 单选：缓存必须有值
          if (cache && cache !== '0') {
            finalValue = cache;
          }
        }

        // 如果没有有效缓存，再用 props.modelValue，否则默认第一个
        if (finalValue !== null) {
          emit('update:modelValue', finalValue);
        } else if (
          !props.modelValue ||
          (Array.isArray(props.modelValue) && props.modelValue.length === 0)
        ) {
          emit(
            'update:modelValue',
            props.multiple ? [data.value[0].tenant_id] : data.value[0].tenant_id
          );
        }
      }

      // 👇 放在 loadSites() 函数的最后 emit('loaded') 之前
      // ✅ 同步全选与半选状态（需延时执行）
      if (props.multiple) {
        nextTick(() => {
          const currentValue = Array.isArray(props.modelValue)
            ? props.modelValue
            : Array.isArray(finalValue)
              ? finalValue
              : [];
          const selectedCount = currentValue.length;
          const total = data.value.length;
          checkAll.value = selectedCount === total;
          isIndeterminate.value = selectedCount > 0 && selectedCount < total;
        });
      }

      emit('loaded');
    } catch (e) {
      EleMessage.error(e.message);
    }
  };

  onMounted(loadSites);
</script>
